<template>
  <!-- 课程管理 -->
  <div class="course">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.course_delete" @click="handleDelete">删 除</el-button>
          <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permissionList" @click="handleExport">导 出</el-button>
        </template>

        //绑定关联课件
        <template slot="idsLabel">
          <span style="color:#F56C6C">*</span><span>课件:</span>
        </template>
        <template slot="idsForm">
          <el-form label-width="0px">
            <el-button type="success" size="small" @click="handleCourseWare">选择课件</el-button>
            <span v-if="courseWareTagsErr" class="courseWare_error">请选择课件</span>
            <div class="courseWare_list">
              <el-tag :key="index" v-for="(tag, index) in courseWareTags" closable :disable-transitions="false"
                      @close="closeCourseWareTag(index)">{{tag.zlbt}}
              </el-tag>
            </div>
          </el-form>
        </template>

      </avue-crud>

      <!-- 关联课件弹窗 -->
      <el-dialog title="关联课件" :visible.sync="dialogCourseWare" append-to-body @close='closeDialog' width="1200px" class="courseWareManager">
        <avue-crud :option="courseWareOption"
                   :table-loading="courseWareLoading"
                   :data="courseWareData"
                   :page.sync="courseWarePage"
                   ref="courseWareCrud"
                   @search-change="courseWareSearchChange"
                   @search-reset="courseWareSearchReset"
                   @selection-change="courseWareSelectionChange"
                   @current-change="courseWareCurrentChange"
                   @size-change="courseWareSizeChange">
        </avue-crud>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="chooseCourseWare()">确 定</el-button>
        </span>
      </el-dialog>


    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update,getkj,remove,getCourseWareSList} from "@/api/jypx/educourse/course";
  import {mapGetters} from "vuex";
  import {getToken} from "@/util/auth";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "培训类别",
              prop: "pxlb",
              type: "select",
              align: "center",
              dataType: "number",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=pxlb",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请选择培训类别",
                trigger: "change",

              }]
            },

            {
              label: "课程名称",
              prop: "kcmc",
              align: "center",
              search: true,
              slot: false,
              rules: [{
                required: true,
                message: "请选择课程名称",
                trigger: "blur",
              }]
            },
            {
              label: "试题数量",
              prop: "stsl",
              align: "center",
              hide: false,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: true,
            },
            {
              label: "试题更新时间",
              prop: "kjgxsj",
              align: "center",
              hide: false,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: true,
            },
            {
              label: "课程学时(分钟)",
              prop: "kcxs",
              align: "center",
              labelWidth:120,
              rules: [{
                required: true,
                message: "请输入课程学时",
                trigger: "blur"
              }]
            },
            {
              label: "资料标题",
              prop: "zlbt",
              align: "center",
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              hide: true
            },

            {
              label: "绑定课件",
              prop: "ids",
              align: "center",
              hide: true,
              viewDisplay: false,
              formslot:true,
              labelslot:true
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            }

          ]
        },
        data: [],

        //课件
        dialogCourseWare: false,
        courseWareQuery: {},
        courseWareLoading: true,
        courseWarePage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        courseWareSelectionList: [],
        courseWareData: [],
        courseWareTags: [],
        courseWareTagsErr: false,
        selectCourseWare: {},
        courseWareOption: {
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          menu: false,
          addBtn: false,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          refreshBtn: false,
          columnBtn: false,
          column: [
            {
              label: "资料标题",
              prop: "zlbt",
              align: "center",
              search: true
            },
            {
              label: "所属类别",
              prop: "sslb",
              align: "center",
            },
           /* {
              label: "文件类型",
              prop: "wjlx",
              align: "center",
            },*/
            {
              label: "文件类型",
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=courseware_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              prop: "wjlx",
              align: "center",

            },
            {
              label: "教程简介",
              prop: "jcjj",
              align: "center",
            },
          ]
        },

      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.course_add, true),
          viewBtn: this.vaildData(this.permission.course_view, true),
          delBtn: this.vaildData(this.permission.course_delete, true),
          editBtn: this.vaildData(this.permission.course_edit, true)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {

      //打开选择课件弹窗
      handleCourseWare(){
        this.dialogCourseWare = true;
        this.courseWareOnLoad(this.courseWarePage);
      },


      // 关闭课件弹窗
      closeDialog(){
        this.dialogCourseWare = false;
        this.courseWarePage.currentPage = 1;
        this.courseWareSelectionClear();
      },

      // 课件获取表格数据
      courseWareOnLoad(page, params = {}) {
        this.courseWareLoading = true;
        getCourseWareSList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.courseWarePage.total = data.total;
          this.courseWareData = data.records;
          this.courseWareLoading = false;
          if(this.selectCourseWare !== undefined && JSON.stringify(this.selectCourseWare) !== "{}" && this.courseWareTags.length !== 0) {
            this.$nextTick(() => {
              this.courseWareData.forEach(row => {
                if(this.selectCourseWare[row.id] !== undefined) {
                  this.$refs.courseWareCrud.toggleRowSelection(row, true);
                }
              })
            })
          }
        });
      },

      //课件清空勾选
      courseWareSelectionClear(){
        this.courseWareSelectionList = [];
        this.$refs.courseWareCrud.toggleSelection();
      },

      //选择课件
      chooseCourseWare(){
        var pageSelectIds = [];
        var pageAllIds = [];
        this.courseWareSelectionList.forEach(item => {
          this.selectCourseWare[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.courseWareData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(let id in this.selectCourseWare) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectCourseWare[id];
          }
        }
        if(this.selectCourseWare === undefined || JSON.stringify(this.selectCourseWare) === "{}") {
          this.$message.warning("请选择课件");
          return;
        }
        this.courseWareTagsErr = false;
        this.courseWareTags = [];
        for(let id in this.selectCourseWare) {
          this.courseWareTags.push(this.selectCourseWare[id]);
        }
        this.closeDialog();
      },

      //课件搜索条件改变事件
      courseWareSearchChange(params, done){
        this.courseWareQuery = params;
        this.courseWarePage.currentPage = 1;
        this.courseWareOnLoad(this.courseWarePage,params);
        done();
      },

      // 课件清空搜索条件
      courseWareSearchReset(){
        this.courseWareQuery = {};
        this.courseWareOnLoad(this.courseWarePage);
      },

      //课件勾选
      courseWareSelectionChange(list){
        this.courseWareSelectionList = list;
      },

      //课件换页数
      courseWareCurrentChange(currentPage){
        const pageSelectIds = [];
        const pageAllIds = [];
        this.courseWareSelectionList.forEach(item => {
          this.selectCourseWare[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.courseWareData.forEach(item => {
          pageAllIds.push(item.id);
        });
        /*for(let id in this.selectCourseWare) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectCourseWare[id];
          }
        }*/
        for(var id in this.selectCourseWare) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectCourseWare[id];
          }
        }
        this.courseWarePage.currentPage = currentPage;
        this.courseWareOnLoad(this.courseWarePage)
      },

      //课件换每页显示数量
      courseWareSizeChange(pageSize){
        this.courseWarePage.pageSize = pageSize;
        this.courseWareOnLoad(this.courseWarePage)
      },

      // 删除某一个CourseWare标签
      closeCourseWareTag(index){
        this.courseWareTags.splice(index,1);
        if(this.courseWareTags.length === 0){
          this.courseWareTagsErr = true;
        }
      },

      //导出模板
      handleTemplate() {
        window.open(`/api/eduCourse/course/export-template?${this.website.tokenHeader}=${getToken()}`);
      },

      //导出
      handleExport() {
        this.$confirm("是否导出课程信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/eduCourse/course/export-Course?${this.website.tokenHeader}=${getToken()}`);
        });
      },

      //新增
      rowSave(row, done, loading) {
        if(this.courseWareTags.length === 0){
          this.courseWareTagsErr = true;
          loading();
          return;
        }
        delete row.zlbt;
        var idsArr = [];
        this.courseWareTags.forEach(item => {
          idsArr.push(item.id);
        });
        row.ids = idsArr.join(",");
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
        /*add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });*/
      },

      //编辑修改
      rowUpdate(row, index, done, loading) {
        var idsArr = [];
        var updateData = {
          id: row.id,
          zlbt: row.zlbt,
          pxlb: row.pxlb,
          kcmc: row.kcmc,
          kcxs: row.kcxs,
          kcxf: row.kcxf,
          ygkssfbd: row.ygkssfbd,
          kj: row.kj,
          bladeDeptId: row.bladeDeptId,
          tenantId: row.tenantId,
          createUser: row.createUser,
          createDept: row.createDept,
          ids: ""
        };
        this.courseWareTags.forEach(item =>{
          idsArr.push(item.id);
        });
        updateData.ids = idsArr.join(",");

        update(updateData).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        },error => {
          window.console.log(error);
          loading();
        });
        /*update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });*/
      },

      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },

      beforeOpen(done, type) {
        switch(type) {
          case 'add':
           /* this.dialogType =''*/
            done();
            break
          case 'edit':
           /* this.dialogType =''*/
            getDetail(this.form.id).then(res => {
              this.form = res.data.data;
            });
            done();
            break
          case 'view':
           /* this.dialogType = type;*/
            done();
            break
          default:
            break
        }
        this.courseWareTagsErr = false;
        this.courseWareTags = [];
        this.selectCourseWare = {};
        if (type === "edit") {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            this.form.courseWares.forEach(item => {
              this.courseWareTags.push(item);
              this.selectCourseWare[item.id] = item;
            });
          });
        }
        done();
      },

      /*beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            console.log(this.form)
          });
        }
        done();
      },*/

      // 清空搜索条件
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },

      // 搜索条件改变事件
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },

      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },

      // 获取表格数据
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss">
  .courseDialog {
    .el-form-item__label {
      width: 100px !important;
    }
    .avue-form__row {
      .el-form-item__content {
        margin-left: 100px !important;
      }
    }
  }
</style>

<style>
  .courseWare_error{
    color: #f56c6c;
    font-size: 12px;
    margin-left: 5px;
  }
</style>















